package cn.itcast.controller.system;

import cn.itcast.controller.BaseController;
import cn.itcast.domain.system.Dept;
import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {
  @Autowired
    private DeptService deptService;

  @RequestMapping(value = "/list",name = "进入部门管理页面")

    public String findAll(@RequestParam(defaultValue = "1",name = "page")Integer pageNum,@RequestParam(defaultValue = "10")Integer pageSize){
   PageInfo<Dept> pageInfo= deptService.findPage(getCompanyId(),pageNum,pageSize);
   request.setAttribute("page",pageInfo);
   return "system/dept/dept-list";
  }
    @RequestMapping(value = "/toAdd",name ="进入部门新增页面")
    @RequiresPermissions("新增部门")
    public String toAdd(){

        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }

    @RequestMapping(value = "/edit",name ="保存部门方法")
    public String edit(Dept dept){
      if(dept.getParent().getId().equals("")){
          dept.getParent().setId(null);
      }
        if (StringUtils.isEmpty(dept.getId())){
            //id为空说明是新增
            dept.setCompanyId(getCompanyId());
            dept.setCompanyName(getCompanyName());
            dept.setId(UUID.randomUUID().toString());
            deptService.save(dept);
        }
        else {
            //id不为空则说明为修改
            deptService.update(dept);
        }
        return "redirect:/system/dept/list.do";
    }
    @RequestMapping(value = "/toUpdate",name ="进入部门修改页面")
    @RequiresPermissions("修改部门")
    public String toUpdate(String id){
        Dept dept=deptService.findById(id);
        request.setAttribute("dept",dept);
        List<Dept> deptList = deptService.findAll(getCompanyId());
        request.setAttribute("deptList",deptList);
        return "system/dept/dept-add";
    }
    @RequestMapping(value = "/delete",name ="删除部门信息")
    @RequiresPermissions("删除部门")
    public String delete(String id){
        deptService.deleteById(id);
        return "redirect:/system/dept/list.do";
    }
}
